package day;

import java.util.ArrayList;
import java.util.List;

public class P68 {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> resultList = new ArrayList<>();

        List<String> rowList = new ArrayList<>();
        int length = 0;
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            int len = length + word.length();
            if (len == maxWidth) { //正好
                rowList.add(word);
                resultList.add(String.join(" ", rowList));
                rowList.clear();
                length = 0;
            } else if (len < maxWidth) {//不够长
                if (i == words.length - 1) {//最后一行
                    rowList.add(word);
                    String s = String.join(" ", rowList);
                    StringBuilder sb = new StringBuilder();
                    sb.append(s);
                    while (sb.length() < maxWidth) {
                        sb.append(" ");
                    }
                    resultList.add(sb.toString());
                } else {//不是最后一行
                    rowList.add(word);
                    length += word.length() + 1;
                }
            } else { //超长
                if (rowList.size() == 1) {
                    StringBuilder sb = new StringBuilder(rowList.get(0));
                    while(sb.length()<maxWidth){
                        sb.append(" ");
                    }
                    resultList.add(sb.toString());
                } else {
                    int avgWhiteSpace = (maxWidth - length + rowList.size()) / (rowList.size() - 1);
                    int leftWhiteSpace = (maxWidth - length + rowList.size()) % (rowList.size() - 1);
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < leftWhiteSpace; j++) {
                        sb.append(rowList.get(j));
                        int tmp = avgWhiteSpace + 1;
                        while (tmp-- > 0) {
                            sb.append(" ");
                        }
                    }
                    for (int j = leftWhiteSpace; j < rowList.size(); j++) {
                        sb.append(rowList.get(j));
                        int tmp = j == rowList.size() - 1 ? 0 : avgWhiteSpace;
                        while (tmp-- > 0) {
                            sb.append(" ");
                        }
                    }
                    resultList.add(sb.toString());
                }
                rowList.clear();
                length = 0;
                i--;
            }

        }
        return resultList;
    }

    public static void main(String[] args) {
        List<String> strings = new P68().fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 16);
        for (String str : strings) {
            System.out.println(str);
        }
    }
}
